package com.zzyl.intercept;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.PathMatcherUtil;
import com.zzyl.utils.ThreadLocalUtil;
import com.zzyl.vo.MenuVo;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 管理端拦截器
 */
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(JwtTokenInterceptor.class);
    @Autowired
    private JwtTokenProperties jwtTokenProperties;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;




    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        //获取token
        String token = request.getHeader("Authorization");

        //解析token
        Claims claims = JwtUtil.parseJWT(jwtTokenProperties.getSecretKey(), token);

        Long id = Long.valueOf(claims.get("id").toString());
        if (ObjectUtil.isEmpty(id)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        log.info("用户信息：{}", id);


        //////////
        //1.先查询redis，如果有，直接比较，如果没有，查询数据库，然后存入redis
        String redisKey = "zzyl:user:resource:path:" + id ;
        String redisData = stringRedisTemplate.opsForValue().get(redisKey);
        List<String> requestPaths = null;
        //如果redis中没有数据，查询数据库
        if (StrUtil.isBlank(redisData)) {
            requestPaths = resourceMapper.selectListByUserId(id); //查询所有资源路径
            //将数据转json字符串，存入redis
            stringRedisTemplate.opsForValue().set(redisKey, JSON.toJSONString(requestPaths));
            log.info("根据用户id查询数据库权限资源");
        }else {
            //如果redis中有数据，将数据转为list
            requestPaths = JSON.parseObject(redisData, List.class);
            log.info("根据用户id查询redis权限资源");
        }

        //根据用户id查询对应的菜单
        String url = request.getMethod() + request.getRequestURI();        //获取请求路径
        if (!PathMatcherUtil.match(requestPaths, url)) {                    //判断请求路径是否在用户的资源路径中
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }


        //将用户id存入ThreadLocal
        ThreadLocalUtil.set(id);

        //放行、拦截
        return true;
    }

}